import { useState } from 'react';
import { 
    Alert,
    Box,
    Button,
    Card,
    CardContent,
    Chip,
    Grid,
    Paper,
    Stack,
    TextField,
    Typography,
    Snackbar
} from '@mui/material';
import ToolPageTemplate from '@/components/ToolPageTemplate';
import NetworkCheckIcon from '@mui/icons-material/NetworkCheck';
import CheckCircleIcon from '@mui/icons-material/CheckCircle';
import ErrorIcon from '@mui/icons-material/Error';
import PlayArrowIcon from '@mui/icons-material/PlayArrow';

interface TestResult {
    method: string;
    success: boolean;
    status?: number;
    data?: any;
    error?: string;
    timestamp: string;
}

const CorsTestPage = () => {
    const [apiUrl, setApiUrl] = useState('http://localhost:8080');
    const [testResults, setTestResults] = useState<TestResult[]>([]);
    const [isLoading, setIsLoading] = useState(false);
    const [snackbarOpen, setSnackbarOpen] = useState(false);
    const [snackbarMessage, setSnackbarMessage] = useState('');

    const addTestResult = (result: TestResult) => {
        setTestResults(prev => [result, ...prev.slice(0, 9)]); // 保留最近10个结果
    };

    const testCorsRequest = async (method: string, endpoint: string, data?: any) => {
        const timestamp = new Date().toLocaleString();
        const url = `${apiUrl}${endpoint}`;
        
        try {
            const options: RequestInit = {
                method,
                headers: {
                    'Content-Type': 'application/json',
                    'X-Requested-With': 'XMLHttpRequest',
                },
                credentials: 'include', // 测试携带凭证
            };

            if (data && (method === 'POST' || method === 'PUT')) {
                options.body = JSON.stringify(data);
            }

            const response = await fetch(url, options);
            const responseData = await response.json();

            addTestResult({
                method,
                success: response.ok,
                status: response.status,
                data: responseData,
                timestamp
            });

            if (response.ok) {
                setSnackbarMessage(`${method} 请求成功`);
                setSnackbarOpen(true);
            }
        } catch (error) {
            addTestResult({
                method,
                success: false,
                error: error instanceof Error ? error.message : String(error),
                timestamp
            });
        }
    };

    const runAllTests = async () => {
        setIsLoading(true);
        setTestResults([]);

        try {
            // 依次测试各种HTTP方法
            await testCorsRequest('GET', '/utils/cors/test');
            await new Promise(resolve => setTimeout(resolve, 500));

            await testCorsRequest('POST', '/utils/cors/test', { test: 'data', timestamp: Date.now() });
            await new Promise(resolve => setTimeout(resolve, 500));

            await testCorsRequest('PUT', '/utils/cors/test', { test: 'update', timestamp: Date.now() });
            await new Promise(resolve => setTimeout(resolve, 500));

            await testCorsRequest('DELETE', '/utils/cors/test');
            await new Promise(resolve => setTimeout(resolve, 500));

            await testCorsRequest('GET', '/utils/cors/config');

            setSnackbarMessage('所有CORS测试完成');
            setSnackbarOpen(true);
        } catch (error) {
            setSnackbarMessage('测试过程中发生错误');
            setSnackbarOpen(true);
        } finally {
            setIsLoading(false);
        }
    };

    const getStatusChip = (result: TestResult) => {
        if (result.success) {
            return (
                <Chip 
                    icon={<CheckCircleIcon />} 
                    label={`成功 (${result.status})`} 
                    color="success" 
                    size="small" 
                />
            );
        } else {
            return (
                <Chip 
                    icon={<ErrorIcon />} 
                    label="失败" 
                    color="error" 
                    size="small" 
                />
            );
        }
    };

    return (
        <ToolPageTemplate 
            title="CORS 跨域测试"
            description="测试后端API的跨域配置是否正常工作"
            category="开发工具"
            categoryColor="#ff9800"
        >
            {/* 配置区域 */}
            <Paper 
                elevation={0} 
                sx={{ 
                    p: 3, 
                    mb: 4, 
                    borderRadius: 3, 
                    border: '1px solid', 
                    borderColor: 'divider'
                }}
            >
                <Typography 
                    variant="h6" 
                    sx={{ 
                        mb: 3, 
                        fontWeight: 700,
                        display: 'flex',
                        alignItems: 'center',
                        gap: 1
                    }}
                >
                    <NetworkCheckIcon color="primary" />
                    CORS 测试配置
                </Typography>

                <Grid container spacing={3} alignItems="center">
                    <Grid item xs={12} md={8}>
                        <TextField
                            fullWidth
                            label="后端API地址"
                            value={apiUrl}
                            onChange={(e) => setApiUrl(e.target.value)}
                            placeholder="http://localhost:8080"
                            helperText="请输入后端服务的完整地址"
                        />
                    </Grid>
                    <Grid item xs={12} md={4}>
                        <Button
                            variant="contained"
                            size="large"
                            fullWidth
                            startIcon={<PlayArrowIcon />}
                            onClick={runAllTests}
                            disabled={isLoading}
                            sx={{ 
                                borderRadius: '25px',
                                py: 1.5,
                                textTransform: 'none',
                                fontWeight: 600
                            }}
                        >
                            {isLoading ? '测试中...' : '开始测试'}
                        </Button>
                    </Grid>
                </Grid>
            </Paper>

            {/* 测试结果 */}
            {testResults.length > 0 && (
                <Paper 
                    elevation={0} 
                    sx={{ 
                        p: 3, 
                        borderRadius: 3, 
                        border: '1px solid', 
                        borderColor: 'divider'
                    }}
                >
                    <Typography 
                        variant="h6" 
                        sx={{ 
                            mb: 3, 
                            fontWeight: 700,
                            display: 'flex',
                            alignItems: 'center',
                            gap: 1
                        }}
                    >
                        🎯 测试结果
                    </Typography>

                    <Stack spacing={2}>
                        {testResults.map((result, index) => (
                            <Card key={index} variant="outlined">
                                <CardContent>
                                    <Box sx={{ 
                                        display: 'flex', 
                                        justifyContent: 'space-between', 
                                        alignItems: 'flex-start',
                                        mb: 2 
                                    }}>
                                        <Box sx={{ display: 'flex', alignItems: 'center', gap: 2 }}>
                                            <Chip 
                                                label={result.method} 
                                                color="primary" 
                                                size="small" 
                                            />
                                            {getStatusChip(result)}
                                        </Box>
                                        <Typography variant="caption" color="text.secondary">
                                            {result.timestamp}
                                        </Typography>
                                    </Box>

                                    {result.success && result.data && (
                                        <Box sx={{ 
                                            mt: 2, 
                                            p: 2, 
                                            bgcolor: 'grey.50', 
                                            borderRadius: 1,
                                            maxHeight: 200,
                                            overflow: 'auto'
                                        }}>
                                            <Typography variant="body2" component="pre" sx={{ fontSize: '0.75rem' }}>
                                                {JSON.stringify(result.data, null, 2)}
                                            </Typography>
                                        </Box>
                                    )}

                                    {!result.success && result.error && (
                                        <Alert severity="error" sx={{ mt: 2 }}>
                                            错误: {result.error}
                                        </Alert>
                                    )}
                                </CardContent>
                            </Card>
                        ))}
                    </Stack>
                </Paper>
            )}

            {/* 使用说明 */}
            <Paper 
                elevation={0} 
                sx={{ 
                    p: 3, 
                    mt: 4, 
                    borderRadius: 3, 
                    border: '1px solid', 
                    borderColor: 'divider',
                    bgcolor: 'info.main',
                    color: 'info.contrastText'
                }}
            >
                <Typography variant="h6" sx={{ mb: 2, fontWeight: 600 }}>
                    📝 使用说明
                </Typography>
                <Stack spacing={1}>
                    <Typography variant="body2">
                        • 此工具用于测试后端API的CORS跨域配置
                    </Typography>
                    <Typography variant="body2">
                        • 测试包含GET、POST、PUT、DELETE等常用HTTP方法
                    </Typography>
                    <Typography variant="body2">
                        • 确保后端服务已启动且可访问
                    </Typography>
                    <Typography variant="body2">
                        • 如果测试失败，请检查后端CORS配置和网络连接
                    </Typography>
                </Stack>
            </Paper>

            <Snackbar
                open={snackbarOpen}
                autoHideDuration={3000}
                onClose={() => setSnackbarOpen(false)}
                anchorOrigin={{ vertical: 'bottom', horizontal: 'center' }}
            >
                <Alert severity="success" sx={{ width: '100%' }}>
                    {snackbarMessage}
                </Alert>
            </Snackbar>
        </ToolPageTemplate>
    );
};

export default CorsTestPage;